package org.dromara.system.controller.system;

import lombok.RequiredArgsConstructor;
import org.dromara.common.oss.core.OssClient;
import org.dromara.common.oss.factory.OssFactory;
import org.dromara.common.web.core.BaseController;
import org.dromara.system.domain.SysSolutionDoc;
import org.dromara.system.mapper.SysSolutionDocMapper;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import jakarta.servlet.http.HttpServletResponse;

/**
 * PDF解决方案预览控制器
 * 预览主PDF与同目录的子PDF（相对路径）
 */
@RequiredArgsConstructor
@RestController
@RequestMapping("/system/pdf-solution")
public class SysPdfSolutionController extends BaseController {

    private final SysSolutionDocMapper solutionDocMapper;

    /**
     * 访问同方案内的子PDF（相对路径）
     */
    @GetMapping("/file/{docId}/{*fileName}")
    public void previewSub(@PathVariable Long docId, @PathVariable String fileName, HttpServletResponse response) {
        SysSolutionDoc solutionDoc = solutionDocMapper.selectById(docId);
        if (solutionDoc == null) {
            response.setStatus(HttpStatus.NOT_FOUND.value());
            return;
        }
        // 安全校验：仅允许访问当前方案目录下的PDF
        if (fileName == null
            || fileName.contains("..")
            || fileName.startsWith("/")
            || fileName.startsWith("\\")
            || !fileName.toLowerCase().endsWith(".pdf")) {
            response.setStatus(HttpStatus.BAD_REQUEST.value());
            return;
        }
        // 兼容前端可能传入的前导"./"
        if (fileName.startsWith("./")) {
            fileName = fileName.substring(2);
        }
        String fileKey = solutionDoc.getFolderPath() + fileName;
        streamPdf(fileKey, fileName, response);
    }

    private void streamPdf(String fileKey, String fileName, HttpServletResponse response) {
        try {
            response.setContentType("application/pdf");
            // 设置内联预览，处理中文文件名（与用户端一致）
            String encoded = java.net.URLEncoder.encode(fileName, java.nio.charset.StandardCharsets.UTF_8.name()).replace("+", "%20");
            response.setHeader("Content-Disposition", "inline; filename*=UTF-8''" + encoded);
            OssClient ossClient = OssFactory.instance();
            ossClient.download(fileKey, response.getOutputStream(), response::setContentLengthLong);
        } catch (Exception e) {
            response.setStatus(HttpStatus.INTERNAL_SERVER_ERROR.value());
        }
    }
}


